<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="「力扣」第 104 题：求一棵二叉树的最大深度（简单）, 算法与数据结构入门教程">
    <meta name="description" content="Java、Python3 语言实现，「专题」教程持续更新中...">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>「力扣」第 104 题：求一棵二叉树的最大深度（简单） | 算法与数据结构入门教程</title>
    <link rel="icon" type="image/png" href="/leetcode-algo/favicon.png">

    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/leetcode-algo/css/my.css">

    <script src="/leetcode-algo/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/leetcode-algo/atom.xml" title="算法与数据结构入门教程" type="application/atom+xml">
<link rel="stylesheet" href="/leetcode-algo/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/leetcode-algo/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/leetcode-algo/" class="waves-effect waves-light">
                    
                    <img src="/leetcode-algo/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">算法与数据结构入门教程</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/leetcode-algo/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/leetcode-algo/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">算法与数据结构入门教程</div>
        <div class="logo-desc">
            
            Java、Python3 语言实现，「专题」教程持续更新中...
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/leetcode-algo/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/leetcode-algo/medias/featureimages/13.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">「力扣」第 104 题：求一棵二叉树的最大深度（简单）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/leetcode-algo/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    .toc-fixed .toc-link::before{
        position: fixed!important;/*当toc的位置改为fixed时，.toc-link::before也要改为fixed*/
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/leetcode-algo/tags/%E9%80%92%E5%BD%92/">
                                <span class="chip bg-color">递归</span>
                            </a>
                        
                            <a href="/leetcode-algo/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/">
                                <span class="chip bg-color">二叉树</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-12%EF%BC%9A%E6%A0%91/" class="post-category">
                                专题 12：树
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2017-11-28
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="「力扣」第-106-题：从中序与后序遍历序列构造二叉树"><a href="#「力扣」第-106-题：从中序与后序遍历序列构造二叉树" class="headerlink" title="「力扣」第 106 题：从中序与后序遍历序列构造二叉树"></a>「力扣」第 106 题：从中序与后序遍历序列构造二叉树</h2><ul>
<li>链接：<a href="https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal" target="_blank" rel="noopener">https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal</a></li>
<li>我写的题解地址：<a href="https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/hou-xu-bian-li-python-dai-ma-java-dai-ma-by-liwe-2/" target="_blank" rel="noopener">https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/hou-xu-bian-li-python-dai-ma-java-dai-ma-by-liwe-2/</a></li>
</ul>
<blockquote>
<p>根据一棵树的中序遍历与后序遍历构造二叉树。</p>
<p>注意:<br>你可以假设树中没有重复的元素。</p>
<p>例如，给出</p>
<pre><code>中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]</code></pre><p>返回如下的二叉树：</p>
<pre><code>   3
  / \
 9  20
   /  \
  15   7</code></pre></blockquote>
<p>来源：力扣（LeetCode）</p>
<p>著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。</p>
<pre><code># https://www.bilibili.com/video/av7420546?from=search&amp;seid=6242384381313003008
# 前序遍历的第 1 个点肯定是根结点
# 参考资料：https://articles.leetcode.com/construct-binary-tree-from-inorder-and-preorder-postorder-traversal/</code></pre><h1 id="LeetCode-第-106-题："><a href="#LeetCode-第-106-题：" class="headerlink" title="LeetCode 第 106 题："></a>LeetCode 第 106 题：</h1><p>二叉树相关的很多问题的解决思路都有分治法的思想在里面。</p>
<p>我们再复习一下分治法的思想：<strong>把原问题拆解成若干个与原问题结构相同但规模更小的子问题，待子问题解决以后，原问题就得以解决</strong>，“归并排序” 和 “快速排序” 都是分治法思想的应用，其中 “归并排序” 先无脑地“分”，在 “合” 的时候就麻烦一些；“快速排序” 开始在 partition 上花了很多时间，即在 “分” 上使了很多劲，然后就递归处理下去就好了，没有在 “合” 上再花时间。</p>
<p>以题目中给出的例子为例，讲解如何构建二叉树。</p>
<blockquote>
<p>中序遍历 <code>inorder = [9,3,15,20,7]</code><br>后序遍历 <code>postorder = [9,15,7,20,3]</code></p>
</blockquote>
<p><img src="https://pic.leetcode-cn.com/5dcc2ad3599fffb757d2746278fc2cba0a9bdf79e1e452bb4885ccb8c72e557d-image.png" alt="image.png"></p>
<p>图画完以后才发现这个例子不太好，数组长度多一些就能把思路展现得更清楚了，各位客官老爷将就看一下啦。或者可以看一下我写的 <a href="https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/" target="_blank" rel="noopener">「力扣」第 105 题</a> 的 <a href="https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/qian-xu-bian-li-python-dai-ma-java-dai-ma-by-liwei/" target="_blank" rel="noopener">题解</a> ，两道问题的解法是一样的。</p>
<p><strong>注意</strong>：这道问题其实并不难，我们在草稿纸上写写画画，就能把思路想清楚，但是在编码上会有一些小陷阱，在计算索引边界值要认真一些。</p>
<p>下面给出两种写法，区别在于空间复杂度：</p>
<h3 id="方法一：在递归方法中，传入数组的拷贝"><a href="#方法一：在递归方法中，传入数组的拷贝" class="headerlink" title="方法一：在递归方法中，传入数组的拷贝"></a>方法一：在递归方法中，传入数组的拷贝</h3><p>该方法在计算索引的时候会稍微容易一些。</p>
<p>Python 代码：</p>
<pre class="line-numbers language-Python"><code class="language-Python">class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def buildTree(self, inorder, postorder):
        assert len(inorder) == len(postorder)

        if len(inorder) == 0:
            return None
        if len(inorder) == 1:
            # 这里要返回结点，而不是返回具体的数
            return TreeNode(inorder[0])
        # 后序遍历的最后一个结点就是根结点
        root = TreeNode(postorder[-1])
        # 在中序遍历中找到根结点的索引，得到左右子树的一个划分
        pos = inorder.index(postorder[-1])
        # 这里的列表切片使用的是复制值，使用了一些空间，因此空间复杂度是 O(N)
        root.left = self.buildTree(inorder[:pos], postorder[:pos])
        root.right = self.buildTree(inorder[pos + 1:], postorder[pos:-1])<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>Java 代码：</p>
<pre class="line-numbers language-Java"><code class="language-Java">import java.util.Arrays;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class Solution {
    /**
     * @param inorder   中序遍历序列
     * @param postorder 后序遍历序列
     * @return
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {

        int inlen = inorder.length;
        int postlen = postorder.length;

        assert inlen == postlen;

        if (inlen == 0) {
            return null;
        }
        if (inlen == 1) {
            return new TreeNode(inorder[0]);
        }

        // 后序遍历的最后一个结点就是根结点
        int rootVal = postorder[postlen - 1];
        // 在中序遍历中找到根结点的索引，得到左右子树的一个划分
        int dividePoint = 0;
        for (int i = 0; i < inlen; i++) {
            if (inorder[i] == rootVal) {
                dividePoint = i;
                break;
            }
        }
        TreeNode rootNode = new TreeNode(rootVal);
        // Arrays.copyOfRange() 方法的第 1 个参数是源数组
        // 第 2 个参数是源数组的起始位置（可以取到）
        // 第 3 个参数是源数组的起始位置（不可以取到）
        // 这里复制了数组，使用了一些空间，因此空间复杂度是 O(N)
        rootNode.left = buildTree(Arrays.copyOfRange(inorder, 0, dividePoint), Arrays.copyOfRange(postorder, 0, dividePoint));
        rootNode.right = buildTree(Arrays.copyOfRange(inorder, dividePoint + 1, inlen), Arrays.copyOfRange(postorder, dividePoint, postlen - 1));
        return rootNode;
    }
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>复杂度分析：</strong></p>
<ul>
<li>时间复杂度：$O(N)$，这里 $N$ 是二叉树的结点个数。</li>
<li>空间复杂度：$O(N)$。</li>
</ul>
<h3 id="方法二：在递归方法中，传入子数组的边界索引"><a href="#方法二：在递归方法中，传入子数组的边界索引" class="headerlink" title="方法二：在递归方法中，传入子数组的边界索引"></a>方法二：在递归方法中，传入子数组的边界索引</h3><p><strong>注意</strong>：在递归方法中，有一个数组的边界索引，得通过计算得到，计算的依据是递归方法传入的“中序遍历数组”（的子数组）和“后序遍历数组”（的子数组）的长度是一样的。我的办法是解方程计算未知数，哈哈，傻呼呼的。具体需要计算哪个参数我在下面的代码中已经注明了。</p>
<p>Python 代码：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">class</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>object<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>val <span class="token operator">=</span> x
        self<span class="token punctuation">.</span>left <span class="token operator">=</span> None
        self<span class="token punctuation">.</span>right <span class="token operator">=</span> None


<span class="token keyword">class</span> <span class="token class-name">Solution</span><span class="token punctuation">:</span>
    <span class="token keyword">def</span> <span class="token function">__init__</span><span class="token punctuation">(</span>self<span class="token punctuation">)</span><span class="token punctuation">:</span>
        self<span class="token punctuation">.</span>inorder <span class="token operator">=</span> None
        self<span class="token punctuation">.</span>postorder <span class="token operator">=</span> None

    <span class="token keyword">def</span> <span class="token function">buildTree</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> inorder<span class="token punctuation">,</span> postorder<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">assert</span> len<span class="token punctuation">(</span>inorder<span class="token punctuation">)</span> <span class="token operator">==</span> len<span class="token punctuation">(</span>postorder<span class="token punctuation">)</span>
        size <span class="token operator">=</span> len<span class="token punctuation">(</span>inorder<span class="token punctuation">)</span>

        self<span class="token punctuation">.</span>inorder <span class="token operator">=</span> inorder
        self<span class="token punctuation">.</span>postorder <span class="token operator">=</span> postorder
        <span class="token keyword">return</span> self<span class="token punctuation">.</span>__dfs<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> size <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> size <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span>

    <span class="token keyword">def</span> <span class="token function">__dfs</span><span class="token punctuation">(</span>self<span class="token punctuation">,</span> in_l<span class="token punctuation">,</span> in_r<span class="token punctuation">,</span> post_l<span class="token punctuation">,</span> post_r<span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> in_l <span class="token operator">></span> in_r <span class="token operator">or</span> post_l <span class="token operator">></span> post_r<span class="token punctuation">:</span>
            <span class="token keyword">return</span> None

        val <span class="token operator">=</span> self<span class="token punctuation">.</span>postorder<span class="token punctuation">[</span>post_r<span class="token punctuation">]</span>
        <span class="token comment" spellcheck="true"># 后序遍历的最后一个结点就是根结点</span>
        root <span class="token operator">=</span> TreeNode<span class="token punctuation">(</span>val<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 在中序遍历中找到根结点的索引，得到左右子树的一个划分</span>
        pos <span class="token operator">=</span> self<span class="token punctuation">.</span>inorder<span class="token punctuation">.</span>index<span class="token punctuation">(</span>val<span class="token punctuation">)</span>

        <span class="token comment" spellcheck="true"># 注意：第 4 个参数是计算出来的，依据：两边区间长度相等</span>
        root<span class="token punctuation">.</span>left <span class="token operator">=</span> self<span class="token punctuation">.</span>__dfs<span class="token punctuation">(</span>in_l<span class="token punctuation">,</span> pos <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> post_l<span class="token punctuation">,</span> pos <span class="token operator">-</span> <span class="token number">1</span> <span class="token operator">-</span> in_l <span class="token operator">+</span> post_l<span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 注意：第 3 个参数是计算出来的，依据：两边区间长度相等</span>
        root<span class="token punctuation">.</span>right <span class="token operator">=</span> self<span class="token punctuation">.</span>__dfs<span class="token punctuation">(</span>pos <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> in_r<span class="token punctuation">,</span> post_r <span class="token operator">-</span> in_r <span class="token operator">+</span> pos<span class="token punctuation">,</span> post_r <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span>
        <span class="token keyword">return</span> root<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>Java 代码：</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">class</span> <span class="token class-name">TreeNode</span> <span class="token punctuation">{</span>
    <span class="token keyword">int</span> val<span class="token punctuation">;</span>
    TreeNode left<span class="token punctuation">;</span>
    TreeNode right<span class="token punctuation">;</span>

    <span class="token function">TreeNode</span><span class="token punctuation">(</span><span class="token keyword">int</span> x<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        val <span class="token operator">=</span> x<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Solution</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">;</span>


    <span class="token keyword">public</span> TreeNode <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>inorder <span class="token operator">=</span> inorder<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>postorder <span class="token operator">=</span> postorder<span class="token punctuation">;</span>
        <span class="token keyword">int</span> len <span class="token operator">=</span> inorder<span class="token punctuation">.</span>length<span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token function">dfs</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> len <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> len <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>


    <span class="token keyword">private</span> TreeNode <span class="token function">dfs</span><span class="token punctuation">(</span><span class="token keyword">int</span> inl<span class="token punctuation">,</span> <span class="token keyword">int</span> inr<span class="token punctuation">,</span> <span class="token keyword">int</span> postl<span class="token punctuation">,</span> <span class="token keyword">int</span> postr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>inl <span class="token operator">></span> inr <span class="token operator">||</span> postl <span class="token operator">></span> postr<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> null<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token keyword">int</span> val <span class="token operator">=</span> postorder<span class="token punctuation">[</span>postr<span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> k <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> inl<span class="token punctuation">;</span> i <span class="token operator">&lt;</span> inr <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>inorder<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">==</span> val<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                k <span class="token operator">=</span> i<span class="token punctuation">;</span>
                <span class="token keyword">break</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>

        TreeNode root <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>val<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">// 注意：第 4 个参数是计算出来的，依据：两边区间长度相等</span>
        root<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token function">dfs</span><span class="token punctuation">(</span>inl<span class="token punctuation">,</span> k <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span> postl<span class="token punctuation">,</span> k <span class="token operator">-</span> <span class="token number">1</span> <span class="token operator">-</span> inl <span class="token operator">+</span> postl<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">// 注意：第 3 个参数是计算出来的，依据：两边区间长度相等</span>
        root<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token function">dfs</span><span class="token punctuation">(</span>k <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> inr<span class="token punctuation">,</span> postr <span class="token operator">+</span> k <span class="token operator">-</span> inr<span class="token punctuation">,</span> postr <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> root<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">}</span><span class="token punctuation">;</span>

        Solution solution <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Solution</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        TreeNode res <span class="token operator">=</span> solution<span class="token punctuation">.</span><span class="token function">buildTree</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> postorder<span class="token punctuation">)</span><span class="token punctuation">;</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>复杂度分析：</strong></p>
<ul>
<li>时间复杂度：$O(N)$，这里 $N$ 是二叉树的结点个数。</li>
<li>空间复杂度：$O(1)$。</li>
</ul>
<h1 id="题目描述（中等难度）"><a href="#题目描述（中等难度）" class="headerlink" title="题目描述（中等难度）"></a>题目描述（中等难度）</h1><p>我写的题解地址：</p>
<p><img src="https://windliang.oss-cn-beijing.aliyuncs.com/106.jpg" alt=""></p>
<p>根据二叉树的中序遍历和后序遍历还原二叉树。</p>
<h1 id="思路分析"><a href="#思路分析" class="headerlink" title="思路分析"></a>思路分析</h1><p>可以先看一下 <a href="https://leetcode.wang/leetcode-105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.html" target="_blank" rel="noopener">105 题</a>，直接在 105 题的基础上改了，大家也可以先根据 105 题改一改。</p>
<p>105 题给的是先序遍历和中序遍历，这里把先序遍历换成了后序遍历。</p>
<p>区别在于先序遍历的顺序是 根节点 -&gt; 左子树 -&gt; 右子树。</p>
<p>后序遍历的顺序是 左子树 -&gt; 右子树 -&gt; 根节点。</p>
<p>我们当然还是先确定根节点，然后在中序遍历中找根节点的位置，然后分出左子树和右子树。</p>
<p>对于之前的解法一，传数组的两个边界，影响不大，只要重新计算边界就可以了。</p>
<p>但是对于另外两种解法，利用 stop 和栈的算法，之前都是通过遍历前序遍历的数组实现的。所以构造过程是根节点，左子树，右子树。</p>
<p>但这里如果是后序遍历，我们先找根节点，所以相当于从右往左遍历，这样的顺序的话就成了，根节点 -&gt; 右子树 -&gt; 左子树，所以我们会先生成右子树，再生成左子树。</p>
<h1 id="解法一"><a href="#解法一" class="headerlink" title="解法一"></a>解法一</h1><p>常规解法，利用递归，传递左子树和右子树的数组范围即可。</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">public</span> TreeNode <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    HashMap<span class="token operator">&lt;</span>Integer<span class="token punctuation">,</span> Integer<span class="token operator">></span> map <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token operator">&lt;</span><span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> inorder<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        map<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>inorder<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> inorder<span class="token punctuation">.</span>length<span class="token punctuation">,</span> postorder<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> postorder<span class="token punctuation">.</span>length<span class="token punctuation">,</span> map<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">private</span> TreeNode <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">,</span> <span class="token keyword">int</span> i_start<span class="token punctuation">,</span> <span class="token keyword">int</span> i_end<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">,</span> <span class="token keyword">int</span> p_start<span class="token punctuation">,</span> <span class="token keyword">int</span> p_end<span class="token punctuation">,</span>
                                 HashMap<span class="token operator">&lt;</span>Integer<span class="token punctuation">,</span> Integer<span class="token operator">></span> map<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>p_start <span class="token operator">==</span> p_end<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> null<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">int</span> root_val <span class="token operator">=</span> postorder<span class="token punctuation">[</span>p_end <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    TreeNode root <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>root_val<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> i_root_index <span class="token operator">=</span> map<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>root_val<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> leftNum <span class="token operator">=</span> i_root_index <span class="token operator">-</span> i_start<span class="token punctuation">;</span>
    root<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> i_start<span class="token punctuation">,</span> i_root_index<span class="token punctuation">,</span> postorder<span class="token punctuation">,</span> p_start<span class="token punctuation">,</span> p_start <span class="token operator">+</span> leftNum<span class="token punctuation">,</span> map<span class="token punctuation">)</span><span class="token punctuation">;</span>
    root<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> i_root_index <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">,</span> i_end<span class="token punctuation">,</span> postorder<span class="token punctuation">,</span> p_start <span class="token operator">+</span> leftNum<span class="token punctuation">,</span> p_end <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">,</span>
                                 map<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> root<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h1 id="解法二-stop-值"><a href="#解法二-stop-值" class="headerlink" title="解法二 stop 值"></a>解法二 stop 值</h1><p>这里的话，之前说了，递归的话得先构造右子树再构造左子树，此外各种指针，也应该从末尾向零走。</p>
<p>视线从右往左看。</p>
<pre class="line-numbers language-java"><code class="language-java">    <span class="token number">3</span>
   <span class="token operator">/</span> \
  <span class="token number">9</span>  <span class="token number">20</span>
    <span class="token operator">/</span>  \
   <span class="token number">15</span>   <span class="token number">7</span>

s 初始化一个树中所有的数字都不会相等的数，所以代码中用了一个 <span class="token keyword">long</span> 来表示
<span class="token operator">&lt;</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span>
中序
  <span class="token number">9</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">7</span>
<span class="token operator">^</span>               <span class="token operator">^</span>
s               i

后序
<span class="token number">9</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">7</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token number">3</span>
              <span class="token operator">^</span>  
              p
<span class="token operator">&lt;</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">--</span><span class="token operator">-</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><code>p</code> 和 <code>i</code> 都从右往左进行遍历，所以 <code>p</code> 开始产生的每次都是右子树的根节点。之前代码里的<code>++</code>要相应的改成<code>--</code>。</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">int</span> post<span class="token punctuation">;</span>
<span class="token keyword">int</span> in<span class="token punctuation">;</span> 
<span class="token keyword">public</span> TreeNode <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    post <span class="token operator">=</span> postorder<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
    in <span class="token operator">=</span> inorder<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> postorder<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token keyword">long</span><span class="token punctuation">)</span> Integer<span class="token punctuation">.</span>MIN_VALUE <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">private</span> TreeNode <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">,</span> <span class="token keyword">long</span> stop<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>post <span class="token operator">==</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> null<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>inorder<span class="token punctuation">[</span>in<span class="token punctuation">]</span> <span class="token operator">==</span> stop<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        in<span class="token operator">--</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> null<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">int</span> root_val <span class="token operator">=</span> postorder<span class="token punctuation">[</span>post<span class="token operator">--</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
    TreeNode root <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>root_val<span class="token punctuation">)</span><span class="token punctuation">;</span>
    root<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> postorder<span class="token punctuation">,</span> root_val<span class="token punctuation">)</span><span class="token punctuation">;</span>
    root<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token function">buildTreeHelper</span><span class="token punctuation">(</span>inorder<span class="token punctuation">,</span> postorder<span class="token punctuation">,</span> stop<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> root<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h1 id="解法三-栈"><a href="#解法三-栈" class="headerlink" title="解法三 栈"></a>解法三 栈</h1><p>之前解法是构造左子树、左子树、左子树，出现相等，构造一颗右子树。这里相应的要改成构造右子树、右子树、右子树，出现相等，构造一颗左子树。和解法二一样，两个指针的话也是从末尾到头部进行。</p>
<pre class="line-numbers language-java"><code class="language-java"><span class="token keyword">public</span> TreeNode <span class="token function">buildTree</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> inorder<span class="token punctuation">,</span> <span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> postorder<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>postorder<span class="token punctuation">.</span>length <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> null<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    Stack<span class="token operator">&lt;</span>TreeNode<span class="token operator">></span> roots <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Stack</span><span class="token operator">&lt;</span>TreeNode<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> post <span class="token operator">=</span> postorder<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">int</span> in <span class="token operator">=</span> inorder<span class="token punctuation">.</span>length <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
    TreeNode curRoot <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>postorder<span class="token punctuation">[</span>post<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    TreeNode root <span class="token operator">=</span> curRoot<span class="token punctuation">;</span>
    roots<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>curRoot<span class="token punctuation">)</span><span class="token punctuation">;</span>
    post<span class="token operator">--</span><span class="token punctuation">;</span>
    <span class="token keyword">while</span> <span class="token punctuation">(</span>post <span class="token operator">>=</span>  <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>curRoot<span class="token punctuation">.</span>val <span class="token operator">==</span> inorder<span class="token punctuation">[</span>in<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span>roots<span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> roots<span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>val <span class="token operator">==</span> inorder<span class="token punctuation">[</span>in<span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                curRoot <span class="token operator">=</span> roots<span class="token punctuation">.</span><span class="token function">peek</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                roots<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                in<span class="token operator">--</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            curRoot<span class="token punctuation">.</span>left <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>postorder<span class="token punctuation">[</span>post<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            curRoot <span class="token operator">=</span> curRoot<span class="token punctuation">.</span>left<span class="token punctuation">;</span>
            roots<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>curRoot<span class="token punctuation">)</span><span class="token punctuation">;</span>
            post<span class="token operator">--</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            curRoot<span class="token punctuation">.</span>right <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">TreeNode</span><span class="token punctuation">(</span>postorder<span class="token punctuation">[</span>post<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            curRoot <span class="token operator">=</span> curRoot<span class="token punctuation">.</span>right<span class="token punctuation">;</span>
            roots<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>curRoot<span class="token punctuation">)</span><span class="token punctuation">;</span>
            post<span class="token operator">--</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> root<span class="token punctuation">;</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h1 id="总"><a href="#总" class="headerlink" title="总"></a>总</h1><p>理解了 <a href="https://leetcode.wang/leetcode-105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.html" target="_blank" rel="noopener">105 题</a> 的话，这道题很快就出来了，完全是 105 题的逆向思考。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者：
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo" rel="external nofollow noreferrer">liweiwei1419</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接：
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo/2017/11/28/leetcode-algo/0106-construct-binary-tree-from-inorder-and-postorder-traversal/">https://liweiwei1419.gitee.io/leetcode-algo/2017/11/28/leetcode-algo/0106-construct-binary-tree-from-inorder-and-postorder-traversal/</a>
                    <!-- GitHub 用配置
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo/leetcode-algo/2017/11/28/leetcode-algo/0106-construct-binary-tree-from-inorder-and-postorder-traversal/">https://liweiwei1419.gitee.io/leetcode-algo/leetcode-algo/2017/11/28/leetcode-algo/0106-construct-binary-tree-from-inorder-and-postorder-traversal/</a>
                    -->
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明：
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://liweiwei1419.gitee.io/leetcode-algo" target="_blank">liweiwei1419</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/leetcode-algo/tags/%E9%80%92%E5%BD%92/">
                                    <span class="chip bg-color">递归</span>
                                </a>
                            
                                <a href="/leetcode-algo/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/">
                                    <span class="chip bg-color">二叉树</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/leetcode-algo/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/leetcode-algo/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/leetcode-algo/medias/reward/alipayimg.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/leetcode-algo/medias/reward/wechatpayimg.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/leetcode-algo/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/leetcode-algo/libs/valine/av-min.js"></script>
<script src="/leetcode-algo/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 't85BdPqKV8IDpevPmRGUSquP-gzGzoHsz',
        appKey: 'AIarytPiYajpQ31kGdAMfVQ8',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/leetcode-algo/2017/11/29/leetcode-algo/0108-convert-sorted-array-to-binary-search-tree/">
                    <div class="card-image">
                        
                        
                        <img src="/leetcode-algo/medias/featureimages/8.jpg" class="responsive-img" alt="「力扣」第 108 题：将有序数组转换为二叉搜索树（简单）">
                        
                        <span class="card-title">「力扣」第 108 题：将有序数组转换为二叉搜索树（简单）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            「力扣」第 108 题：将有序数组转换为二叉搜索树（简单）
链接：https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree


将一个按照升序排列
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2017-11-29
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-12%EF%BC%9A%E6%A0%91/" class="post-category">
                                    专题 12：树
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/leetcode-algo/tags/%E9%80%92%E5%BD%92/">
                        <span class="chip bg-color">递归</span>
                    </a>
                    
                    <a href="/leetcode-algo/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/">
                        <span class="chip bg-color">二叉树</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/leetcode-algo/2017/11/27/leetcode-algo/0105-construct-binary-tree-from-preorder-and-inorder-traversal/">
                    <div class="card-image">
                        
                        
                        <img src="/leetcode-algo/medias/featureimages/19.jpg" class="responsive-img" alt="「力扣」第 105 题：从前序与中序遍历序列构造二叉树（中等）">
                        
                        <span class="card-title">「力扣」第 105 题：从前序与中序遍历序列构造二叉树（中等）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            「力扣」第 105 题：从前序与中序遍历序列构造二叉树（中等）
抓住「前序遍历序列」与「中序遍历序列」的定义，递归构建二叉树。并且通过画图计算出需要使用的子区间的下标。最后看一眼复杂度，使用「空间换时间」的思路优化。


链接
题解链接（含
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2017-11-27
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/leetcode-algo/categories/%E4%B8%93%E9%A2%98-12%EF%BC%9A%E6%A0%91/" class="post-category">
                                    专题 12：树
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/leetcode-algo/tags/%E9%80%92%E5%BD%92/">
                        <span class="chip bg-color">递归</span>
                    </a>
                    
                    <a href="/leetcode-algo/tags/%E4%BA%8C%E5%8F%89%E6%A0%91/">
                        <span class="chip bg-color">二叉树</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/leetcode-algo/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/leetcode-algo/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="https://liweiwei1419.gitee.io/leetcode-algo" target="_blank">liweiwei1419</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/liweiwei1419" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:liweiwei1419@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=121088825" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 121088825" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>



    <a href="https://weibo.com/u/2194939432" class="tooltipped" target="_blank" data-tooltip="关注我的微博: https://weibo.com/u/2194939432" data-position="top" data-delay="50">
        <i class="fab fa-weibo"></i>
    </a>





    <a href="/leetcode-algo/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/leetcode-algo/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/leetcode-algo/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/leetcode-algo/libs/materialize/materialize.min.js"></script>
    <script src="/leetcode-algo/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/leetcode-algo/libs/aos/aos.js"></script>
    <script src="/leetcode-algo/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/leetcode-algo/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/leetcode-algo/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/leetcode-algo/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/leetcode-algo/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/leetcode-algo/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
